from usr import uQR
from usr import st7789v
import log


class TesTuQrClass():
    def __init__(self):
        self.lcd_st7789v = st7789v.ST7789V(240, 240)
        self.qUr_log = log.basicConfig()
        self.qUr_log = log.getLogger("uQr")
        self.qUr_log.setLevel(log.INFO)

    def init(self, url="https://www.baidu.com/"):
        self.qr = uQR.QRCode()
        self.qr.add_data(url)
        self.matrix = self.qr.get_matrix()
        self.Qr_wight = int(len(self.matrix[0]))
        self.Qr_hight = int(len(self.matrix))

        self.pixel_w = int(240 / self.Qr_wight)
        self.pixel_h = int(240 / self.Qr_hight)
        # 首先计算像素点的大小

        self.qUr_log.info("二维码长宽  {} * {}".format(self.Qr_wight,
                                                  self.Qr_hight))
        self.qUr_log.info("二维码像素长度  {} * {}".format(self.pixel_w,
                                                    self.pixel_h))

    # 生成一列像素点的数据
    def creat_pix_buf(self, _Qr_h):
        line_image_buf = ()
        for _Qr_w in range(self.Qr_wight):
            if self.matrix[_Qr_h][_Qr_w] is True:
                # 画像素点
                line_image_buf = line_image_buf + self.pix_color_tuple * self.pixel_w
            else:
                # 留白的像素点
                line_image_buf = line_image_buf + self.bk_color_tuple * self.pixel_w
        return line_image_buf * self.pixel_h

    def write(self,
              postion_x=0,
              postion_y=0,
              count=4,
              bk_rgb565=0xFFFF,
              pix_rgb565=0x0000):
        # 获取像素点的元组值
        self.bk_color_tuple = (int(bk_rgb565 & 0x00FF),
                               int(bk_rgb565 >> 8 & 0x00FF))
        self.pix_color_tuple = (int(pix_rgb565 & 0x00FF),
                                int(pix_rgb565 >> 8 & 0x00FF))
        self.qUr_log.info("二维码像素点颜色元组  {} ".format(self.pix_color_tuple))
        self.qUr_log.info("二维码背景颜色  {} ".format(self.bk_color_tuple))
        for i in range(self.Qr_hight):
            self.lcd_st7789v.lcd_show_image(
                bytearray(self.creat_pix_buf(i)),
                x=postion_x,  # wight
                y=postion_y + i * self.pixel_h,
                width=self.Qr_wight * self.pixel_w,
                heigth=self.pixel_h)
        pass


def test_qUR():
    bk_rgb565 = 0xFFFF
    # 获取对应的图像的buf
    Test = TesTuQrClass()
    Test.init(
        url=
        "https://www.baidu.com/s?ie=UTF-8&wd=Python%20%E5%85%83%E7%BB%84%E7%9B%B8%E5%8A%A0%20%E5%86%85%E5%AD%98%E6%98%AF%E6%80%8E%E4%B9%88%E5%A4%84%E7%90%86%E7%9A%84%EF%BC%9F",
    )
    # 没有添加，位置的界限检测,需要自行判断一下。
    Test.write(postion_x=20,
               postion_y=20,
               bk_rgb565=bk_rgb565,
               pix_rgb565=0xF800)


if __name__ == "__main__":
    test_qUR()
    pass
